package com.jubaozan.service.platform.decorator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jubaozan.c3.framework.utils.ObjectUtil;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.dao.youme.domain.Store;
import com.jubaozan.dao.youme.domain.StoreUser;
import com.jubaozan.dao.youme.domain.StoreUserAudit;
import com.jubaozan.dao.youme.service.StoreService;
import com.jubaozan.dao.youme.service.StoreUserAuditService;
import com.jubaozan.dao.youme.service.StoreUserService;
import com.jubaozan.feign.level.LevelFeignService;
import com.jubaozan.feign.level.vo.LevelVO;
import com.jubaozan.feign.level.vo.RuleVO;
import com.jubaozan.feign.store.StoreFeignService;
import com.jubaozan.feign.store.vo.StoreUserVO;
import com.jubaozan.feign.user.UserFeignService;
import com.jubaozan.feign.user.vo.UserCreationVO;
import com.jubaozan.feign.user.vo.UserVO;
import com.jubaozan.service.platform.constants.LevelWeightEnum;
import com.jubaozan.service.platform.constants.PlatformStatusEnum;
import com.jubaozan.service.platform.exception.PlatformException;
import com.jubaozan.service.platform.vo.StoreUserRelationVO;
import com.jubaozan.service.platform.vo.TeamInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName TeamRegisterDecorator
 * @Description 团长入驻Decorator
 * @Author SunWei
 * @Version 1.0
 **/
@Slf4j
@Component
public class TeamRegisterDecorator {

    private final UserFeignService userFeignService;

    private final StoreUserService storeUserService;

    private final StoreService storeService;

    private final StoreUserAuditService storeUserAuditService;

    private final LevelFeignService levelFeignService;

    private final StoreFeignService storeFeignService;

    public TeamRegisterDecorator(UserFeignService userFeignService, StoreUserService storeUserService, StoreService storeService, StoreUserAuditService storeUserAuditService, LevelFeignService levelFeignService, StoreFeignService storeFeignService) {

        this.userFeignService = userFeignService;
        this.storeUserService = storeUserService;
        this.storeService = storeService;
        this.storeUserAuditService = storeUserAuditService;
        this.levelFeignService = levelFeignService;
        this.storeFeignService = storeFeignService;
    }

    /**
     * 团长升级资料上传
     * @param teamInfoVO
     * @return
     */
    public Boolean register(TeamInfoVO teamInfoVO){
        UserCreationVO creation = new UserCreationVO();
        BeanUtils.copyProperties(teamInfoVO, creation);
        //调用用户注册接口
        ResultHolder<UserVO> holder = userFeignService.createUser(creation);
        if (!holder.isSuccess() || ObjectUtil.isEmpty(holder.getBody())) {
            throw new PlatformException("创建用户失败!");
        }

        //查询们店用户表信息是否存在（一个平台下面用户只能有一个角色,平台id和用户id组合重复）
        QueryWrapper<StoreUser> queryWrapper = new QueryWrapper<StoreUser>()
                .eq("store_id", teamInfoVO.getStoreId())
                .eq("user_id", holder.getBody().getId());
        StoreUser storeUser = storeUserService.getOne(queryWrapper);
        StoreUserAudit userAudit = new StoreUserAudit();
        if(ObjectUtil.isEmpty(storeUser)){
            //
            //查询门店用户的id
            storeUser = new StoreUser();
            Store store = storeService.getById(teamInfoVO.getStoreId());
            storeUser.setStoreId(teamInfoVO.getStoreId());
            storeUser.setUserId(holder.getBody().getId());
            LevelVO levelVO = levelFeignService.queryLevel(LevelWeightEnum.FANS.getValue(), teamInfoVO.getStoreId()).getBody();
            //确认等级是啥
            storeUser.setLevelId(ObjectUtil.isEmpty(levelVO) ? 1L : levelVO.getId());
            storeUser.setRefereeId(store.getUserId());
            //封装门店用户审核信息
            userAudit.setSourceLevel(LevelWeightEnum.FANS.getValue());
            userAudit.setSourceLevelName(LevelWeightEnum.FANS.getName());
            userAudit.setStoreId(teamInfoVO.getStoreId());
        }else{
            //查询等级id
            LevelVO levelVO = levelFeignService.queryLevelById(storeUser.getLevelId()).getBody();
            //封装门店用户审核信息
            userAudit.setStoreId(storeUser.getStoreId());
            userAudit.setSourceLevel(levelVO.getWeight());
            userAudit.setSourceLevelName(levelVO.getName());
        }
        userAudit.setTargetLevel(teamInfoVO.getWeight());
        userAudit.setTargetLevelName(teamInfoVO.getLevelName());
        userAudit.setStatus(PlatformStatusEnum.WAIT_AUDIT.status());
        userAudit.setRemarks(teamInfoVO.getImages());
        userAudit.setUserId(holder.getBody().getId());

        //保存门店信息
        boolean result = storeUserService.saveOrUpdate(storeUser,new QueryWrapper<StoreUser>().eq("store_id",teamInfoVO.getStoreId()).eq("user_id",holder.getBody().getId()));
        if(result){
            //保存门店审核信息
            result = storeUserAuditService.saveOrUpdate(userAudit,new QueryWrapper<StoreUserAudit>().eq("store_id",teamInfoVO.getStoreId()).eq("user_id",holder.getBody().getId()));
        }
        return result;
    }

    /**
     * 平台查询配置团长升级规则信息
     * @return
     */
    public List<RuleVO> queryRule(Integer weight,Long storeId){
        //获取团长升级规则信息
        List<RuleVO> ruleVOList = levelFeignService.queryRules(weight, storeId).getBody();
        if(CollectionUtils.isEmpty(ruleVOList)){
            throw new PlatformException("团长升级规则信息为空");
        }
        return ruleVOList;
    }

    /**
     *保存升级方式信息
     * @return
     */
    public List<RuleVO> saveRule(Integer weight,Long storeId,List<RuleVO> rules){
        List<RuleVO> ruleVOList = levelFeignService.saveRules(weight, storeId, rules).getBody();
        if(ObjectUtil.isEmpty(ruleVOList)){
            throw new PlatformException("团长升级规则保存失败");
        }
        return ruleVOList;
    }

    /**
     * 查询此用户是否存在绑定关系
     * @param userId
     */
    public StoreUserRelationVO queryStoreUserRelation(Long storeId, Long userId){
        //此用户升级团长时查询此用户是否和其它平台进行关联
        List<StoreUserVO> list = storeFeignService.queryStoreUser(userId).map(object ->{
            return object;
        }).orElseThrow(()-> new PlatformException("用户:"+userId+"不存在平台:"+storeId));

        for (StoreUserVO userVO:list){
            if(!storeId.equals(userVO.getStoreId())){
                ResultHolder<LevelVO> levelVOResultHolder = levelFeignService.queryLevelById(userVO.getLevelId());
                StoreUserRelationVO  relationVO = new StoreUserRelationVO();
                relationVO.setName(levelVOResultHolder.getBody().getName());
                relationVO.setStoreId(userVO.getStoreId());
                relationVO.setWeight(levelVOResultHolder.getBody().getWeight());
                return relationVO;
            }
        }
        return null;
    }
}
